/*
 * @Descripttion:
 * @version:
 * @Author: 刘译蓬
 * @Date: 2022-11-02 14:51:22
 * @LastEditors: 刘译蓬
 * @LastEditTime: 2022-11-03 14:29:56
 */
import {
  Color4,
  DeviceOrientationCamera,
  Engine,
  Scene,
  Vector3,
} from "@babylonjs/core";
import debuggerLayer from "./debuggerLayer";
import modelLoadTest from "./modelLoadTest";
import rtcCamera from "./rtcCamera";
import skyLight from "./skyLight";
import TransparentVideo from "./TransparentVideo";
import "@babylonjs/loaders";
import "@babylonjs/loaders/glTF";
import "@babylonjs/inspector";
export default class MyBabylon {
  canvas: HTMLCanvasElement;
  engine: Engine;
  scene: Scene;
  camera: any;
  video!: TransparentVideo;
  /**
   * @Descripttion: MyBabylon
   * @Author: 刘译蓬
   * @msg: babylon应用实例
   * @param {HTMLCanvasElement} canvas
   * @return {*}
   */
  constructor(canvas: HTMLCanvasElement) {
    // 初始化
    this.canvas = canvas;
    this.engine = new Engine(canvas, true, {}, true);
    this.scene = new Scene(this.engine);
    this.scene.clearColor = new Color4(0.5, 0.7, 1, 1);
    const assumedFramesPerSecond = 60;
    const earthGravity = -9.34;
    this.scene.gravity = new Vector3(
      0,
      earthGravity / assumedFramesPerSecond,
      0
    ); // 设置场景重力(模拟地球)
    this.scene.collisionsEnabled = true; // 开启碰撞检测
    // 调试工具
    debuggerLayer(this.scene);
    // 默认天光
    skyLight(this.scene);
    // 相机
    this.camera = new DeviceOrientationCamera(
      "camera",
      new Vector3(9, 0.9, 11),
      this.scene
    );
    this.camera.minZ = 0;
    this.camera.setTarget(new Vector3(0, 0, 10));
    this.camera.attachControl(canvas, true);
    // 加载模型
    modelLoadTest(this.scene, "/public/scene1chaifen.glb");
    // rtc相机
    rtcCamera((cameraVideo: HTMLVideoElement) => {
        // 透明视频
       this.video = new TransparentVideo(
        "video",
        { width: 3.2, height: 2 },
        cameraVideo,
        this.camera,
        this.scene,
        false
      );
    });
    this.RenderLoop(this.engine, this.scene); // 执行渲染循环
  }
  /**
   * @Descripttion: RenderLoop
   * @Author: 刘译蓬
   * @msg: 渲染循环
   * @param {Engine} engine
   * @param {Scene} scene
   * @return {*}
   */
  RenderLoop(engine: Engine, scene: Scene) {
    // 添加窗口变化事件监听
    window.addEventListener("resize", () => {
      engine.resize();
    });
    // 执行循环
    engine.runRenderLoop(() => {
      scene.render();
    });
  }
}
